﻿using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Vroom.SchemaReporter
{
	class SchemaReporterBootsrap
	{

		#region props

		private Server  SmoSqlServer { get; set; }
		private Database SmoSqlDb	 { get; set; }

		private string DatabaseHost { get; set; }
		private string DatabaseName { get; set; }
		private string SchemaList	{ get; set; }
		private string ConnString	{ get; set; }

		#endregion

		static void Main(string[] args)
		{
			SchemaReporterBootsrap schemaReporterBootstrap = new SchemaReporterBootsrap();
			schemaReporterBootstrap.Init();
			schemaReporterBootstrap.GenerateReport();
		}

		private void Init()
		{
			#region Prepare SMO

			DatabaseHost =	ConfigurationManager.AppSettings[Const.DatabaseHost];
			DatabaseName =	ConfigurationManager.AppSettings[Const.DatabaseName];
			SchemaList	 =	ConfigurationManager.AppSettings[Const.SchemaList];

			SmoSqlServer = new Server(new ServerConnection(new SqlConnection("Data Source=" + DatabaseHost + ";Initial Catalog=" + DatabaseName + ";Integrated Security=SSPI;")));
			Database db = new Database(SmoSqlServer, DatabaseName);
			db.Refresh();
			SmoSqlDb = db;

			#endregion
		}

		private void GenerateReport()
		{
			StringBuilder sb = new StringBuilder();
			IEnumerable<Table> lstDestinationTables = SmoSqlDb.Tables.Cast<Table>().Where(p => p.Schema == SchemaList).ToList();

			foreach (Table table in lstDestinationTables)
			{
				IEnumerable<Column> cols = table.Columns.Cast<Column>().Where(p => p.Name != "Id" && p.Name != "InsertDate" && p.Name != "RunId" && p.Name != "OpicsId").ToList();
				foreach (Column col in cols)
				{
					string line = table.Name + Const.ONE_DELIM + col.Name + Const.THREE_DELIM + GetDataType(col) + Const.FOUR_DELIM + Environment.NewLine;
					Log(line, ref sb);
				}				
			}
			File.WriteAllText(@"C:\Users\o606633\Desktop\FAM.schema", sb.ToString(), Encoding.ASCII);
		}


		private string GetDataType(Column col)
		{
			string dataType = String.Empty;

			switch (col.DataType.SqlDataType)
			{
				case SqlDataType.Decimal:
					dataType = SqlDataType.Decimal.ToString() + Const.BRACE_OPN + col.DataType.NumericPrecision + "," + col.DataType.NumericScale + Const.BRACE_CLSD;
					break;
				case SqlDataType.VarChar:
					dataType = SqlDataType.VarChar.ToString() + Const.BRACE_OPN + col.DataType.MaximumLength + Const.BRACE_CLSD;
					break;
				default:
					dataType = col.DataType.ToString();
					break;
			}

			return dataType.ToUpper();
		}


		private void Log(string line, ref StringBuilder sb)
		{
			sb.Append(line);
			Console.WriteLine(line);
		}

	}
}
